package com.onec.service.manage.config;

import cn.hutool.crypto.digest.DigestUtil;
import com.onec.service.api.content.RedisKeyContent;
import com.onec.service.api.utils.HttpContextUtil;
import com.onec.service.api.utils.IPUtil;
import com.onec.service.api.utils.RedisKeyUtil;
import com.onec.service.manage.dto.resp.UserToken;
import com.onec.service.manage.entity.*;
import com.onec.service.manage.service.UserLoginService;
import com.onec.service.manage.utils.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

/**
 * token 登录和权限认证
 *
 * @author 26500
 */
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 用于用户查询
     */
    @Autowired
    private UserLoginService loginService;

    /**
     * shiro 配置适用的token
     *
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UserToken;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法
     * 授权模块，获取用户角色和权限。
     *
     * @param token token
     * @return AuthorizationInfo 权限信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection token) {
        Long userId = JwtUtil.getUserId(token.toString());

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 查询用户角色
        List<UserRole> userRoleList = loginService.findUserRoleByUserId(userId);
        if (null == userRoleList || 0 == userRoleList.size()) {
            return simpleAuthorizationInfo;
        }
        for (UserRole userRole : userRoleList) {
            // 查询角色
            RoleInfo roleInfo = loginService.findRoleByRoleId(userRole.getRoleId());
            simpleAuthorizationInfo.addRole(roleInfo.getRoleCode());

            for (RolePermission rolePermission : loginService.findRolePermissionByRoleId(userRole.getRoleId())) {
                PermissionInfo permissionInfo = loginService.findPermissionById(rolePermission.getPermissionId());
                simpleAuthorizationInfo.addStringPermission(permissionInfo.getPermissionCode());
            }
        }
        return simpleAuthorizationInfo;
    }

    /**
     * 用户认证:编写shiro判断逻辑，进行用户认证
     *
     * @param authenticationToken 身份认证 token
     * @return AuthenticationInfo 身份认证信息
     * @throws AuthenticationException 认证相关异常
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 这里的 token是从 JWTFilter 的 executeLogin 方法传递过来的，已经经过了解密
        String token = (String) authenticationToken.getCredentials();
        String username = JwtUtil.getUsername(token);
        Long userId = JwtUtil.getUserId(token);
//
        // 通过redis查看token是否过期
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();

        String proCode = IPUtil.getIpAddr(request) + "_" + userId;
        String loginKey = RedisKeyUtil
                .getKey(RedisKeyContent.SERVICE_MANAGE, RedisKeyContent.SERVICE_MANAGE_LOGIN, proCode);
        String redisToken = stringRedisTemplate.opsForValue().get(loginKey);
        if (redisToken == null || redisToken.equals(DigestUtil.md5Hex(token))) {
            throw new AuthenticationException("token已经过期,请重新获取！");
        }

        if (StringUtils.isBlank(username)) {
            throw new AuthenticationException("token校验不通过");
        }
        // 通过用户id查询用户信息
        UserInfo userInfo = loginService.findUserName(username);

        if (Optional.ofNullable(userInfo).isEmpty()) {
            throw new AuthenticationException("用户名或密码错误");
        }
        if (!JwtUtil.verify(token, username, userInfo.getSalt())) {
            throw new AuthenticationException("token校验不通过");
        }
        return new SimpleAuthenticationInfo(token, token, getName());
    }
}



